﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
/// <summary>
///Base 的摘要说明
/// </summary>
public class Base
{
    public Base()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    //参数设置



    //Appid
    public static string Weixin_Appid = "wx7127ch17a2e59cgb";
    //Appsecret 
    public static string Weixin_Appsecret = "b3d2fa1c4ac97c866eff6b58d82a421e";

    //微信支付分配的商户号
    public static string Weixin_Pay_MCHID = "10010000";

    //商户支付密钥  不知道在哪获取可以登录商户平台：https://pay.weixin.qq.com，然后点击账户设置 => 安全设置 => API安全 点击“设置密钥”按钮
    public static string Weixin_Pay_MerchantKey = "s2gDWR1784jGgYUZ2k1TATGhb3w0Lsgs";


    //证书地址
    public static string cert_url = @"E:\cert\apiclient_cert.p12";





    public static long GenerateTimeStamp(DateTime dt)
    {
        // Default implementation of UNIX time of the current UTC time  
        TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds);
    }

    //生成随机字符
    public static string GenNoncestr(int length)
    {
        Random r = new Random();
        string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        string noncestr = "";
        for (int i = 0; i < length; i++)
        {
            noncestr += str[r.Next(str.Length)];
        }
        return noncestr;
    }




    #region 微信红包
    private static string toMD5(string source)
    {
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");
    }
    public static string GetSignature(string act_name, int max_value, string mch_billno, string mch_id, int min_value, string nick_name, string nonce_str, string remark, string re_openid, string send_name, int total_amount, int total_num, string wishing, string sign = "")
    {
        string signature = "";
        string signature_str = "";
        string client_ip = HttpContext.Current.Request.UserHostAddress;
        string StringA = "";
        //拼接签名算法
        string wxappid = Weixin_Appid;
        StringA += "act_name=" + act_name;
        StringA += "&client_ip=" + client_ip;
        StringA += "&max_value=" + max_value;
        StringA += "&mch_billno=" + mch_billno;
        StringA += "&mch_id=" + mch_id;
        StringA += "&min_value=" + min_value;
        StringA += "&nick_name=" + nick_name;
        StringA += "&nonce_str=" + nonce_str;
        StringA += "&re_openid=" + re_openid;
        StringA += "&remark=" + remark;
        StringA += "&send_name=" + send_name;
        if (sign != "")
            StringA += "&sign=" + sign;
        StringA += "&total_amount=" + total_amount;
        StringA += "&total_num=" + total_num;
        StringA += "&wishing=" + wishing;
        StringA += "&wxappid=" + wxappid;
        signature_str = StringA + "&key=" + Weixin_Pay_MerchantKey;
        signature = toMD5(signature_str).ToUpper();
        return signature;
    }

    /*CheckValidationResult的定义*/
    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        if (errors == SslPolicyErrors.None)
            return true;
        return false;
    }
    public static string Web_Post(string url, string xmldata)
    {
        //证书地址,并且双击apiclient_cert.p12安装证书
        string cert = cert_url;
        string password = Weixin_Pay_MCHID;
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

        //****************注意*********************
        //这里添加 证书要注意，在本地调试的时候
        //本地调试用这个
        //X509Certificate cer = new X509Certificate(cert, password);
        //上传服务器上用这个
        X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        webrequest.ClientCertificates.Add(cer);
        webrequest.Method = "post";
        webrequest.UseDefaultCredentials = true;
        //添加xml数据
        StreamWriter swMessages = new StreamWriter(webrequest.GetRequestStream());
        //写入的流以XMl格式写入
        swMessages.Write(xmldata);
        //关闭写入流
        swMessages.Close();

        HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse();
        Stream stream = webreponse.GetResponseStream();
        string resp = string.Empty;
        using (StreamReader reader = new StreamReader(stream))
        {
            resp = reader.ReadToEnd();
        }
        return resp;


    }
    /// <summary>
    /// 发送红包
    /// </summary>
    /// <param name="openid">用户openid</param>
    /// <param name="nick_name">商户名称</param>
    /// <param name="wishing">祝福语</param>
    /// <param name="act_name">活动名称</param>
    /// <param name="remark">红包备注</param>
    /// <returns></returns>
    public static string GetCachred(string openid, string nick_name, string wishing, string act_name, string remark)
    {
        string nonce_str = GenNoncestr(16);
        string mch_id = Weixin_Pay_MCHID;
        Random r = new Random();
        string mch_billno = mch_id + DateTime.Now.ToString("yyyyMMddHHmmssfff") + r.Next(0, 9);

        //total_amount,min_value,max_value3个值必须是相等的
        int total_amount = 100;
        int min_value = 100;
        int max_value = 100;

        int total_num = 1;
        string send_name = nick_name;//商户名称
        string client_ip = HttpContext.Current.Request.UserHostAddress;
        string wxappid = Weixin_Appid;

        //获得签名
        string signValue = GetSignature(act_name, max_value, mch_billno, mch_id, min_value, nick_name, nonce_str, remark, openid, send_name, total_amount, total_num, wishing);
        string post_data = "";
        post_data += "<xml>";
        post_data += "<sign><![CDATA[" + signValue + "]]></sign>";
        post_data += "<mch_billno><![CDATA[" + mch_billno + "]]></mch_billno>";
        post_data += "<mch_id>" + mch_id + "</mch_id>";
        post_data += "<wxappid>" + wxappid + "</wxappid>";
        post_data += "<nick_name><![CDATA[" + nick_name + "]]></nick_name>";
        post_data += "<send_name><![CDATA[" + send_name + "]]></send_name>";
        post_data += "<re_openid>" + openid + "</re_openid>";
        post_data += "<total_amount>" + total_amount + "</total_amount>";
        post_data += "<total_num>" + total_num + "</total_num>";
        post_data += "<wishing><![CDATA[" + wishing + "]]></wishing>";
        post_data += "<client_ip><![CDATA[" + client_ip + "]]></client_ip>";
        post_data += "<act_name><![CDATA[" + act_name + "]]></act_name>";
        post_data += "<remark><![CDATA[" + remark + "]]></remark>";
        post_data += "<nonce_str><![CDATA[" + nonce_str + "]]></nonce_str>";
        post_data += "</xml>";
        string post_url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        string request_str = Web_Post(post_url, post_data);
        return request_str;
    }
    #endregion
}